var userManager_page = {};

userManager_page.action = {
    initBody: function () {
        userManager_page.interface.initTablePage();
        userManager_page.action.bindEvent();
    },
    bindEvent: function () {
        $("#addBtn").click(function () {
            // userManager_page.interface.initPlugins();
            userManager_page.interface.initFormPage();
            return false;
        });
        $("#cancel").click(function () {
            userManager_page.action.initBody();
            return false;
        });
        $("#groupName").click(function () {
            userManager_page.interface.initGroupPage();
            return false;
        });
        $("#submitBtn").click(function () {
            userManager_page.action.saveBtnClick();
            return false;
        });
    },
    bindEventClose:function () {
        $(".close").click(function(){
            this.remove();
        })
    },
    // 在做action动作时校验数据data
    checkData:function (action, data) {
        var result = AppComm.data.newResult();

        if((data.groupId==""||data.groupId==null||data.groupId.trim()=="")){
            result.success = false;
            result.error = "所属组织不能为空。";
            return result;
        }
        if (action=='addSubmit') {
            if((data.username==""||data.username==null||data.username.trim()=="")){
                result.success = false;
                result.error = "账号不能为空。";
                return result;
            }
        }

        var flag = 0;
        var params={
            id:data.id,
            operationKey:data.operationKey,
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                if(resultData.data!=null){
                    flag++;
                }
            }
        };

        var checkUrl = "";
        if (action=='editSubmit') {
            checkUrl = AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserNameOutCurrent';
        } else if (action=='addSubmit'){
            checkUrl = AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserName';
        }

        AppComm.ajax.execute({
            'url':checkUrl,
            'data':params,
            'async':false,
            'success':onSuccess
        });

        if(flag>0){
            result.success = false;
            result.error = "该账号已存在。";
        } else {
            result.success = true;
        }
        return result;
    },
    saveBtnClick:function () {
        var params = {
            id:$("#id").val(),
            pswd:$("#pswd").val(),
            username:$("#username").val(),
            fullname:$("#fullname").val(),
            phone:$("#phone").val(),
            email:$("#email").val(),
            comment:$("#comment").val(),
            orderId:$("#orderId").val(),
            groupId:$("#groupId").val(),
            groupName:$("#groupName").val(),
            theme:$("#theme").val(),
        };
        var result = userManager_page.action.checkData(userManager_page.data.action, params);
        if (!result.success) {
            layer.alert(result.error, {
                icon: 0,
                skin: 'layer-ext-moon'
            })
        } else {
            var onSuccess = function (resultData) {
                if (resultData.success) {
                    userManager_page.action.initBody();
                    layer.msg("保存成功！", {icon: 1});
                } else {
                    layer.msg("保存失败！", {icon: 2});
                }
            };
            AppComm.ajax.execute({
                'url':AppComm.url.getBaseURL()+'/userManager/ajax/saveUser',
                'data':params,
                'success':onSuccess
            });
        }
    },
    deleteUser: function (userId) {
        var params = {
            id: userId
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("删除成功！", {icon: 1});
                userManager_page.data.tableIns.reload();
            }
        };
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/userManager/ajax/deleteUser',
            'data': params,
            'success': onSuccess
        });
    },
    saveRoles: function (currUserid, roleIds) {
        var roleD = new Array();
        for (var i=0; i<roleIds.length; i++) {
            roleD.push(roleIds[i].value);
        }
        var ids = roleD.join(",");
        var params= {
            id:currUserid,
            ids:ids
        };
        var onSuccess1 = function (resultData) {
            if (resultData.success) {
                layer.msg("配置成功！", {icon: 1});
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveRolePer',
            'data':params,
            'success':onSuccess1
        });
    }
};
userManager_page.interface = {
    // 加载表格页
    initTablePage: function () {
        var html = template("userManagerList_template");
        $(".userManager_box").html(html);

        layui.use(['table', 'form'], function () {
            var table = layui.table;

            //执行表格渲染
            var tableIns = table.render({
                height: 625,
                url: AppComm.url.getBaseURL() + '/userManager/ajax/getUserManagerList',
                elem: "#tb_list",
                page: true,
                limit: 14,
                loading: true,
                id: 'id',
                cols: [[
                    {
                        field: 'fullname',
                        title: '姓名',
                        //width:200,
                        align: 'left',
                        width:150
                    },
                    {
                        field: 'username',
                        title: '账号',
                        align: 'left',
                        width:100
                    }, {
                        field: 'phone',
                        title: '电话',
                        align: 'left',
                        width:130
                    }, {
                        field: 'email',
                        title: '邮箱',
                        align: 'left',
                        width:150
                    }, {
                        field: 'orderId',
                        title: '排序号',
                        edit: 'text',
                        align: 'left',
                        width:80
                    },{
                        field: 'groupName',
                        title: '所属组织',
                        align: 'left',
                        width:120
                    },
                    {
                        field: 'comment',
                        title: '说明',
                        align: 'left',
                        width:100
                    }, {
                        field: 'operation',
                        title: '操作',
                        fixed: 'right',
                        width: 250,
                        toolbar: '#toolbar'
                    }
                ]]
            });

            userManager_page.data.tableIns = tableIns;

            table.on('tool(tb_list)', function (obj) {
                var rowData = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'editBtn') {
                    userManager_page.interface.initFormPage(rowData.id);
                    userManager_page.action.bindEvent();
                    // layer.alert(rowData.id+'ddsdfsdfsdfsdds',{icon: 3, title:'提示'});
                }
                if (layEvent === 'perBtn') {
                    userManager_page.interface.initPermissionPage(rowData.id);
                    userManager_page.action.bindEvent();
                }
                if (layEvent === 'deleteBtn') {
                    // if(rowData.username=="admin"){
                    //     layer.msg("管理员账号不能删除！！",{icon: 2});
                    // }else{
                        layer.confirm('确定要进行删除吗？', {icon: 3, title: '提示'}, function (index) {
                            userManager_page.action.deleteUser(rowData.id);
                            layer.close(index);
                        }, function (index) {
                            layer.close(index);
                        });
                    // }
                };
                if (layEvent === 'showPer') {

                    var param ={
                        id:rowData.id,
                    };
                    var onSuccess = function (resultData) {
                        if (resultData.success) {
                            var html = template("userManagerList_per", {});
                            var perLayer = layer.open({
                                type: 1,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['800px', '760px'], //宽高
                                offset: '100px',
                                shadeClose: true,
                                content: html
                            });
                            var myChart = echarts.init(document.getElementById('treePer'));
                            myChart.showLoading();
                            var data1 = {
                                    "name": "菜单",
                                    "children": resultData.data.menu
                                };
                            var data2 = {
                                "name": "操作",
                                "children": resultData.data.permission
                            };
                            myChart.hideLoading();

                            myChart.setOption(option = {
                                tooltip: {
                                    trigger: 'item',
                                    triggerOn: 'mousemove'
                                },
                                legend: {
                                    top: '2%',
                                    left: '3%',
                                    orient: 'vertical',
                                    data: [{
                                        name: '菜单',
                                        icon: 'rectangle'
                                    } ,
                                        {
                                            name: '操作',
                                            icon: 'rectangle'
                                        }],
                                    borderColor: '#c23531'
                                },
                                series:[
                                    {
                                        type: 'tree',

                                        name: '菜单',

                                        data: [data1],

                                        top: '5%',
                                        left: '7%',
                                        bottom: '2%',
                                        right: '60%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,

                                        animationDuration: 550,
                                        animationDurationUpdate: 750

                                    },
                                    {
                                        type: 'tree',
                                        name: '操作',
                                        data: [data2],

                                        top: '20%',
                                        left: '60%',
                                        bottom: '22%',
                                        right: '18%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,

                                        animationDuration: 550,
                                        animationDurationUpdate: 750
                                    }
                                ]
                            });
                        }
                    };
                    AppComm.ajax.execute({
                        'url': AppComm.url.getBaseURL() + '/userManager/ajax/getPermissionListByUserId',
                        'data': param,
                        'success': onSuccess
                    });
                }
            });
            table.on('edit(tb_list)', function(obj){
                var param ={
                    id:obj.data.id,
                    orderId:obj.value,
                };
                var onSuccess = function (resultData) {
                    if (resultData.success) {
                        layer.msg("排序已修改！", {icon: 1});
                        userManager_page.action.initBody();
                    } else {
                        lay.msg("修改失败！", {icon: 2});
                    }
                };
                AppComm.ajax.execute({
                    'url': AppComm.url.getBaseURL() + '/userManager/ajax/saveUser',
                    'data': param,
                    'success': onSuccess
                });
            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchForm');
            form.on('submit(searchBtn)', function (data) {
                var postData = {
                    fullname: data.field.fullnameInput
                };
                tableIns.reload({
                    page: {curr:1},
                    where: postData
                });
                return false;
            });
        });

    },
    // 初始化表单页
    initFormPage: function (dataId) {
        if (dataId == undefined || '' == dataId.trim()) {
            // 添加
            var html = template("userManagerForm_template");
            $(".userManager_box").html(html);
            userManager_page.action.bindEvent();
            userManager_page.data.action = "addSubmit";
            // layui.use('form', function(){
            //     var form = layui.form;
                // form.verify({
                //     groupId:function (value) {
                //         if ($.isEmpty(value)) {
                //             return '所属组织不能为空。';
                //         }
                //     },
                //     username:function(value){
                //         if(value==""||value==null){
                //             return "账号不能为空";
                //         }
                //         var flag = 0;
                //         var params={
                //             userName:value,
                //         };
                //         var onSuccess = function (resultData) {
                //             if (resultData.success) {
                //                 if(resultData.data!=null){
                //                     flag++;
                //                 }
                //             }
                //         };
                //         AppComm.ajax.execute({
                //             'url':AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserName',
                //             'data':params,
                //             'async':false,
                //             'success':onSuccess
                //         });
                //         if(flag>0){
                //             return "账号已存在";
                //         }
                //     },
                // });

                // form.on('submit(submitBtn)', function(data){
                //     data.field.fileJson = JSON.stringify(userManager_page.data.imgUpload.getSingleUploadFile());
                //     var onSuccess = function (resultData) {
                //         if (resultData.success) {
                //             layer.msg("保存成功！");
                //             // userManager_page.action.initBody();
                //         } else {
                //             lay.msg("保存失败！");
                //         }
                //     };
                //     AppComm.ajax.execute({
                //         'url': AppComm.url.getBaseURL() + '/userManager/ajax/saveUser',
                //         'data': data.field,
                //         'success': onSuccess
                //     });
                // });
            // });
            //添加页面显示默认的图片
            // $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL() +"/static/comm/img/defaultHead.jpg");
        } else {
            // 编辑
            userManager_page.data.action = "editSubmit";

            layer.load();
            var params = {
                id: dataId
            };
            var onSuccess = function (resultData) {
                layer.closeAll('loading');
                //获取上传头像的url
                // var imgUrl = null;
                // if(resultData.data.unitFile != null){
                //     imgUrl = resultData.data.unitFile.sourceUrl;
                // }
                var html = template("userManagerForm_template", resultData.data);
                $(".userManager_box").html(html);
                // userManager_page.interface.initPlugins();
                //判断头像是否已经上传
                // if(imgUrl == null || imgUrl == ""){
                //     $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL()+"/static/comm/img/defaultHead.jpg");
                // }
                userManager_page.action.bindEvent();
                $("#username_div").remove();
                $("#pswd_div").remove();
                // layui.use('form', function(){
                //     var form = layui.form;
                //     form.verify({
                //         username:function(value){
                //             var flag = 0;
                //             var params={
                //                 id:resultData.data.id,
                //                 userName:value,
                //             };
                //             var onSuccess = function (resultData) {
                //                 if (resultData.success) {
                //                     if(resultData.data!=null){
                //                         flag++;
                //                     }
                //                 }
                //             };
                //             AppComm.ajax.execute({
                //                 'url':AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserNameOutCurrent',
                //                 'data':params,
                //                 'async':false,
                //                 'success':onSuccess
                //             });
                //             if(flag>0){
                //                 return "用户名已存在";
                //             }
                //         },
                //     });
                //
                //     form.on('submit(submitBtn)', function(data){
                //         data.field.id=dataId;
                //         data.field.fileJson = JSON.stringify(userManager_page.data.imgUpload.getSingleUploadFile());
                //         var onSuccess = function (resultData) {
                //             if (resultData.success) {
                //                 layer.msg("保存成功！");
                //                 // userManager_page.action.initBody();
                //             } else {
                //                 lay.msg("保存失败！");
                //             }
                //         };
                //         AppComm.ajax.execute({
                //             'url': AppComm.url.getBaseURL() + '/userManager/ajax/saveUser',
                //             'data': data.field,
                //             'success': onSuccess
                //         });
                //     });
                // });
            };
            AppComm.ajax.execute({
                'url': AppComm.url.getBaseURL() + '/userManager/ajax/getUserById',
                'data': params,
                'success': onSuccess
            });
        }
    },
    //角色授权界面初始化
    initPermissionPage: function (dataId) {

        var html = template("userManagerList_role", {});
        var roleLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '480px', //宽高
            offset: '50px',
            content: html,
            btnAlign: 'c',
            btn: ['提交', '取消'], //可以无限个按钮
            yes: function(index, layero){
                layer.close(roleLayer);
                var getData = userManager_page.data.transfer.getData("transferId");
                userManager_page.action.saveRoles(dataId, getData);
            },
        });
        var onSuccess = function (resultData) {
            console.log(resultData.data);
            if (resultData.success) {
                layui.use(['transfer', 'layer', 'util'], function(){
                    var $ = layui.$
                        ,transfer = layui.transfer
                        ,layer = layui.layer
                        ,util = layui.util;
                    userManager_page.data.transfer = transfer;
                    userManager_page.data.transfer.render({
                        id:'transferId',
                        elem: '#transfer',
                        title: ['未授权角色', '已授权角色'],
                        data: resultData.data.allRoles,
                        value: resultData.data.haveRoles
                    })

                });
            }
        };
        var params = {
            id:dataId
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/getRolesTransfer4User',
            'data':params,
            'success':onSuccess
        });
    },
    //选择组织界面初始化
    initGroupPage: function () {
        var html = template("userManagerList_group", {});
        var groupLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '720px', //宽高
            offset: '50px',
            content: html
        });
        layui.use(['table', 'form'], function () {
            var table = layui.table;
            //执行表格渲染
            var groupTable = table.render({
                elem: "#group_list",
                url: AppComm.url.getBaseURL()+'/groupManager/ajax/getGroupList',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'skip']
                },
                limit: 10,
                heigth:"600px",
                loading: true,
                id: 'group_list',
                cols: [[
                    {
                        field: 'groupName',
                        title: '组织名称',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    },
                    {
                        field: 'parentName',
                        title: '上级组织',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    },
                    {
                        field: 'comment',
                        title: '组织说明',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    }
                ]]
            });

            table.on('tool(group_list)', function (obj) {
                var rowData = obj.data;
                userManager_page.data.currGroupId = rowData.id;
                $("#groupName").val(rowData.groupName);
                $("#groupId").val(rowData.id);
                // var layEvent = obj.event;
                layer.close(groupLayer);

            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchGroupForm');
            form.on('submit(searchGroup)', function (data) {
                var postData = {
                    groupName: data.field.groupNameInput
                };
                groupTable.reload({
                    page: {curr:1},
                    where: postData
                });
                return false;
            });
            return;
        });
    },
    // 初始化相关插件
    initPlugins: function(){
        //初始化图片上传插件
        var imgUpload = new CommonImageUpload("test_imgUpload2");
        userManager_page.data.imgUpload = imgUpload;
        imgUpload.singleImageUploadInit(null);

    },
};

userManager_page.data = {
    'tableIns': undefined,
    roleTable:null,
    imgUpload:null,
    'currGroupId':'',
    'action':"",
    transfer : null
};


AppComm.initFrame(userManager_page);